import {
  Badge,
  Button,
  Card,
  Col,
  DatePicker,
  Divider,
  Dropdown,
  Form,
  Icon,
  Input,
  InputNumber,
  Menu,
  Row,
  Select,
  Popconfirm,
  message,
} from 'antd';
import React, { Component, Fragment } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import moment from 'moment';
import { StateType } from './model';
import StandardTable, { StandardTableColumnProps } from './components/StandardTable';
import OrderForm, { FormValsType } from './components/OrderForm';
import { TableListItem, TableListPagination, TableListParams } from './data.d';
import { download } from '../tradersManagement/utils/commons';
import styles from './style.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = (obj: { [x: string]: string[] }) =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  tradersManagement: StateType;
}

interface TableListState {
  modalVisible: boolean;
  updateModalVisible: boolean;
  expandForm: boolean;
  selectedRows: TableListItem[];
  formValues: { [key: string]: string };
  recordFormValues: Partial<TableListItem>;
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    tradersManagement,
    loading,
    global,
  }: {
    tradersManagement: StateType;
    global: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    tradersManagement,
    global,
    loading: loading.models.rule,
  }),
)
class TableList extends Component<TableListProps, TableListState> {
  state: TableListState = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    recordFormValues: {},
  };

  columns: StandardTableColumnProps[] = [
    {
      title: '公司名称',
      dataIndex: 'name',
    },
    {
      title: '国家',
      dataIndex: 'countryName',
    },
    {
      title: '地址',
      dataIndex: 'address',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>

          <a onClick={() => this.handleModalVisible(true, record)}>查看</a>
          <Divider type="vertical" />
          <Popconfirm
            onConfirm={this.handleDelete.bind(this, record)}
            okText="是"
            cancelText="否"
            placement="leftTop"
            title={'数据删除后将不可以恢复，是否继续删除？'}
          >
            <a href="#">删除</a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'tradersManagement/fetch',
      payload: {
        page: 1,
        size: 10,
      },
    });
  }

  handleStandardTableChange = (
    pagination: Partial<TableListPagination>,
    filtersArg: Record<keyof TableListItem, string[]>,
    sorter: SorterResult<TableListItem>,
  ) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params: Partial<TableListParams> = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      //...filters,
    };
    // if (sorter.field) {
    //   params.sorter = `${sorter.field}_${sorter.order}`;
    // }

    dispatch({
      type: 'tradersManagement/fetch',
      payload: params,
    });
  };

  handleMenuClick = (e: { key: string }) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'tradersManagement/remove',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSearch = () => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      let params = {
        page: 1,
        size: 10,
        ...values,
      };

      dispatch({
        type: 'tradersManagement/fetch',
        payload: params,
      });
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'tradersManagement/fetch',
      payload: { page: 1, size: 10 },
    });
  };

  handleModalVisible = (flag?: boolean, record?: FormValsType) => {
    const { dispatch } = this.props;
    // dispatch({ type: 'tradersManagement/createBuyer', payload: {} });
    if (record) {
      dispatch({ type: 'tradersManagement/getBuyer', payload: { id: record.id } });
    }
    this.setState({
      modalVisible: !!flag,
      recordFormValues: record || {},
    });
  };

  onDownload = record => {
    let url = MC_PATH + '/api/order/' + record.id + '/generate';
    download(url, {});
  };


  handleDelete = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tradersManagement/deleteBuyer',
      payload: {
        id: record.id,
      },
      callback: () => {
        this.handleSearch();
      },
    });
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          {/*<Col md={8} sm={24}>*/}
            {/*<FormItem label="客户名称">*/}
              {/*{getFieldDecorator('cstName')(<Input placeholder="请输入" />)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}
          {/*<Col md={8} sm={24}>*/}
            {/*<FormItem label="订单编号">*/}
              {/*{getFieldDecorator('orderNo')(<Input placeholder="请输入" />)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}
          {/*<Col md={8} sm={24}>*/}
            {/*<span className={styles.submitButtons}>*/}
              {/*<Button type="primary" htmlType="submit" onClick={this.handleSearch}>*/}
                {/*查询*/}
              {/*</Button>*/}
              {/*<Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>*/}
                {/*重置*/}
              {/*</Button>*/}
              {/*<a style={{ marginLeft: 8 }} onClick={this.toggleForm}>*/}
                {/*展开 <Icon type="down" />*/}
              {/*</a>*/}
            {/*</span>*/}
          {/*</Col>*/}
        </Row>
      </Form>
    );
  }

  // renderAdvancedForm() {
  //   const {
  //     form: { getFieldDecorator },
  //   } = this.props;
  //   return (
  //     <Form layout="inline">
  //       <div style={{ overflow: 'hidden' }}>
  //         <div style={{ float: 'right', marginBottom: 24 }}>
  //           <Button type="primary" htmlType="submit" onClick={this.handleSearch}>
  //             查询
  //           </Button>
  //           <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
  //             重置
  //           </Button>
  //           <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
  //             收起 <Icon type="up" />
  //           </a>
  //         </div>
  //       </div>
  //     </Form>
  //   );
  // }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      tradersManagement: { list, pagination },
      loading,
      dispatch,
    } = this.props;
    const data = { list, pagination };

    const { selectedRows, modalVisible, updateModalVisible, recordFormValues } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const methods = {
      handleModalVisible: this.handleModalVisible,
      handleSearch: this.handleSearch,
    };
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          {modalVisible ? (
            <OrderForm
              {...methods}
              {...this.props.tradersManagement}
              dispatch={dispatch}
              updateModalVisible={updateModalVisible}
              recordFormValues={recordFormValues}
            />
          ) : (
            <div className={styles.tableList}>
              <div className={styles.tableListForm}>{this.renderForm()}</div>
              <div className={styles.tableListOperator}>
                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                  新建
                </Button>
                {selectedRows.length > 0 && (
                  <span>
                    <Button>批量操作</Button>
                    <Dropdown overlay={menu}>
                      <Button>
                        更多操作 <Icon type="down" />
                      </Button>
                    </Dropdown>
                  </span>
                )}
              </div>
              <StandardTable
                selectedRows={selectedRows}
                loading={loading}
                data={data}
                columns={this.columns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
